import { memo, ReactElement, useEffect, useState } from "react";
import wrapper from "@/store/index";
import { fetchSuggestList } from "@/store/modules/home";
import { getSearchData } from "@/services/modules/search";
import { IProduct } from "@/services/modules/home";
import styles from "./index.module.scss";
import _ from "lodash";

import type { FC } from "react";
import type { GetServerSideProps } from "next";

import GridView4 from "@/components/GridView4";
import SortBy from "@/components/SortBy";
import BreadCrumb from "@/components/BreadCrumb";

export interface IProps {
  children?: ReactElement;
  q?: string;
  productList?: IProduct[];
}

const Search: FC<IProps> = memo(function (props) {
  const { children, q = "", productList = [] } = props;

  // const [cIndex, setCIndex] = useState(0);

  const linkList = [
    {
      path: "/",
      name: "首页",
    },
    {
      path: null,
      name: q,
    },
  ];

  const sortSelect = [
    {
      id: 164331,
      sort: "default",
      name: "综合",
    },
    {
      id: 164332,
      sort: "price_asc",
      name: "价格低到高",
    },
    {
      id: 164333,
      sort: "price_desc",
      name: "价格高到低",
    },
  ];

  const [nowProductList, setNowProductList] = useState<IProduct[]>([]);

  useEffect(() => {
    setNowProductList([...productList]);
  }, [productList]);

  const handleItemClick = (item: any) => {
    if (item.sort === "price_asc") {
      setNowProductList(_.orderBy(nowProductList, "originalCost", "asc"));
    } else if (item.sort === "price_desc") {
      setNowProductList(_.orderBy(nowProductList, "originalCost", "desc"));
    } else {
      setNowProductList([...productList]);
    }
  };

  return (
    <>
      <div className={styles.container}>
        <div className="wrapper">
          <BreadCrumb linkList={linkList}></BreadCrumb>
          <SortBy
            onItemClick={handleItemClick}
            selectData={sortSelect}
          ></SortBy>
          <GridView4 productList={nowProductList}></GridView4>
        </div>
      </div>
    </>
  );
});

export const getServerSideProps: GetServerSideProps =
  wrapper.getServerSideProps(function (store) {
    return async (context) => {
      await store.dispatch(fetchSuggestList({}));

      const { q } = context.query;
      const res = await getSearchData({
        limit: 60,
        offset: 0,
        key: q as string,
      });

      return {
        props: {
          q: q,
          productList: res.products || [],
        },
      };
    };
  });

export default Search;
Search.displayName = "Search";
